package com.nycreativity.elecreativity.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.nycreativity.elecreativity.entity.ResultData;
import com.nycreativity.elecreativity.util.usersession.UserCache;
import com.nycreativity.elecreativity.util.usersession.LoginUser;
import com.nycreativity.elecreativity.util.usersession.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author ttxxi
 * @description: 请求接口时登录验证的拦截器
 * @create: 2021年3月12日22:33:29
 **/
@Slf4j
public class MyInterceptor implements HandlerInterceptor {

    private static String TOKEN_NAME = "Authorization";


    @Override
    public boolean preHandle(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {
        String accessToken = request.getHeader(TOKEN_NAME);
        // 如果是OPTIONS请求则结束
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            response.setStatus(HttpStatus.NO_CONTENT.value());
            return true;
        }
        if (!ObjectUtils.isEmpty(accessToken)) {
            //验证token判定登录，已经登录则放行
            LoginUser loginUser = UserCache.get(Long.valueOf(accessToken));
            //不为空则存储user信息到threadLocal，方便后面直接取用
            if (!ObjectUtils.isEmpty(loginUser)) {
                UserContext.put(loginUser);
            }

        }
        return true;
    }

    private void setNotLoggedIn(@NotNull HttpServletResponse response) throws IOException {
        //未登录
        log.info("用户未登录或登录信息已过期");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter printWriter = response.getWriter();
        ResultData<String> result = ResultData.FAILED("用户未登录或登录信息已过期");
        printWriter.print(JSONObject.toJSONString(result));
        printWriter.flush();
        printWriter.close();
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //!!!!很重要，每一次结束后必须remove掉，不然会内存泄露
        UserContext.remove();
    }
}
